﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Kugar.Core.SL4.Control
{
    public static class UIElementExtMethod
    {
        /// <summary>
        ///     读取指定控件下所有符合类型的子控件
        /// </summary>
        /// <typeparam name="T">要读取的控件的类型</typeparam>
        /// <param name="parent">父控件对象</param>
        /// <returns></returns>
        public static T[] GetChildControl<T>(this UIElement parent) where T:UIElement
        {
            var tempList = new List<UIElement>();

            GetChildren(parent,typeof(T),ref tempList);

            if (tempList.Count<=1)
            {
                return null;
            }
            else
            {
                var arr = new T[tempList.Count];

                for (int i = 0; i < tempList.Count; i++)
                {
                    arr[i] = (T) tempList[i];
                }

                //return tempList.ChangeType(i => (T) i).ToArray();
                return arr;
            }

        }

        public static T GetParentControl<T>(this UIElement item) where T:UIElement
        {
            if (item != null)
            {
                var parent = (UIElement)VisualTreeHelper.GetParent(item);
                UIElement parentTreeViewItem = parent as T;
                return (parentTreeViewItem != null) ? (parentTreeViewItem as T) : GetParentControl<T>(parent);
            }
            return null;            
        }


        private static void GetChildren(UIElement parent, Type targetType, ref List<UIElement> children)
        {
            int count = VisualTreeHelper.GetChildrenCount(parent);
            if (count > 0)
            {
                for (int i = 0; i < count; i++)
                {
                    UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);
                    if (child.GetType() == targetType)
                    {
                        children.Add(child);
                    }
                    GetChildren(child, targetType, ref children);
                }
            }
        }
    }


    public static class ComboBoxExt
    {
        public static void SelectObject(this ComboBox cmb, object selectValue,Predicate<object> checkfun)
        {
            if (cmb.ItemsSource==null)
            {
                return ;
            }

            if (selectValue==null)
            {
                cmb.SelectedItem = null;
            }

            foreach (var s in cmb.ItemsSource)
            {
                if (checkfun!=null && checkfun(s)==true)
                {
                    cmb.SelectedItem = s;
                }
                else if(s==selectValue)
                {
                    cmb.SelectedItem = s;
                }
            }

        }
    }
}
